<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * BuildingList controller
 */
class BuildingMobileList extends Front_Controller
{

    private $_listURL = "/buildinglist/";

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 3.0版本楼盘列表页
     * @author zephan <zephanliu@gmail.com>
     */
    public function index($cityCode) {

        if (empty($cityCode)) {
            // 默认调整到上海楼盘列表
            redirect($this->_listURL.'shanghai', 'auto', 302);
        }
        $get = $this->input->get();
        $page = isset($get['page']) ? $get['page'] : 1;
        $qd = isset($get['qd']) ? $get['qd'] : 'other';
        $buildingIds = isset($get['id']) ? $get['id'] : '';
        $currentQuery = $this->current_url_query($get);
        if (empty($buildingIds)) {
            // 默认调整到上海楼盘列表
            redirect('/building/'.$cityCode, 'auto', 302);
        }
        // 加载模型
        $this->load->model('hometop/hometop_model');
        $this->load->model('hotcity/hotcity_model');
        $this->load->model('area/area_model');
        $this->load->model('phone/phone_model');
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingsinfo_model');
        $this->load->model('buildings/buildingstag_model');
        $this->load->model('price/price_model');
        $this->load->library('user_agent');

        // 根据板块获取所有已开通的城市
        $citiestmp = $this->area_model->select("area_id,area_name,code,plates")->where('active=1 and deleted=0')->find_all();
        $area_block_name = area_block_name();
        foreach ($citiestmp as $key => $val) {
            $cities[$area_block_name[$val->plates]][] = $val;
        }
        $data['cities'] = $cities;
        // 当前地区类型 0:country,1:province,2:city,3:district
        $city = $this->area_model->select('area_id,area_name,code')->find_by(['code'=>$cityCode, 'area_type'=>2, 'active'=>1]);
        if (!$city) redirect("/", 'auto', '302');
        $data['city'] = $city;
        $url = $this->_listURL.$cityCode;
        //获取楼盘列表
        $buildingTable = $this->buildings_model->get_table();
        $infoTable = $this->buildingsinfo_model->get_table();
        // 楼盘数据基本条件
        $where = "deleted = 0 AND publish = 1";
        // 区域条件
        $where .= " AND city_id = {$city->area_id}";
        if(!empty($buildingIds)){
            $buildingIds = str_replace("，",",",$buildingIds);
            $where .= " AND {$buildingTable}.id in ($buildingIds)";
            $idQuery = "id=$buildingIds";
            $url = $this->_listURL.$cityCode."?".$idQuery;
            $currentUrl = "{$url}".$currentQuery;
        }else{
            $currentUrl = "{$url}?".$currentQuery;
        }
        $limit = 5;
        $buildings = $this->buildings_model->select("*")
                                            ->where($where)
                                            ->join($infoTable, "{$buildingTable}.id = {$infoTable}.building_id")
                                            ->limit($limit, ($page-1)*$limit)
                                            ->order_by("{$buildingTable}.id","DESC")
                                            ->find_all();                                                                
        if ($buildings) {
            foreach ($buildings as $key => $val) {
                $tags = $this->buildingstag_model->tags($val->building_id);
                if ($val->price_desc != '') {
                    $price = $val->price_desc;
                    $number = preg_replace('/\D/s', '', $price);  
                    $buildings[$key]->price_desc = str_replace($number, "<span>¥".number_format($number)."</span>", $price);
                }
                $buildings[$key]->tags = isset($tags['putong']) ? $tags['putong'] : [];
                $district = $this->area_model->select('area_id,area_name')->find($val->district_id);
                $buildings[$key]->district = $district;
                $photos = $this->buildings_model->getBuildingPhotos($val->building_id);
                $buildings[$key]->cover = $photos['cover']['pc'][0];
                $buildings[$key]->ave_price = number_format($val->ave_price);
                //查询改楼盘的分机号
                $phone = $this->phone_model->getPhoneByBuildingId($val->building_id, $qd);
                // $buildings[$key]->pc_phone = $phone['pc']->number;
                // $buildings[$key]->mobile_phone = $phone['mobile']->number;
                //$buildings[$key]->ext_phone = $phone;
                //dump($phone);exit();
                $building_mobile_phone = empty($phone['mobile']) ? '' : $phone['mobile']->number;
                $buildings[$key]->ext_mobile_phone = ($qd=='other' || (!empty($building_mobile_phone) && strlen($building_mobile_phone) <= 5)) ? $val->telephone.','.$building_mobile_phone : $building_mobile_phone;

            }
        }
        // 分页
        $totalRows = $this->buildings_model->select("*")->where($where)->count_all();
        $this->load->library('pagination');
        $this->pager['base_url']    = $currentUrl;
        $this->pager['total_rows']  = $totalRows;
        $this->pager['per_page']    = $limit;
        $this->pager['use_page_numbers'] = true;
        $this->pager['page_query_string'] = true;
        $this->pager['enable_query_strings'] = true;
        $this->pager['query_string_segment'] = 'page';
        $this->pagination->initialize($this->pager);

        $data['current_query'] = $currentQuery;
        $data['buildings'] = $buildings;
        $data['is_mobile'] = $this->agent->is_mobile();
        $data['is_pad'] = stripos($this->agent->mobile, 'pad') === false ? 0 : 1;
        $data['city_code'] = $cityCode;
        $data['list_url'] = $url;
        $data['listurl'] = $this->_listURL;
        $data['ip_address'] = $this->ip_address;
        $data['channel'] = $qd;
        $data['buildingCookieId'] = $this->getLogCookie();
        
        // 加载视图
        $this->load->view('front/building/mobilelist', $data);
    }

    /**
     * 楼盘当前页面的筛选参数
     * @param  array $get get
     * @return string
     * @author zephan <zephanliu@gmail.com>
     */
    private function current_url_query($get) {
        $queryData = [];
        if (isset($get['qd'])) {
            $queryData['qd'] = $get['qd'];
        }
        return http_build_query($queryData);
    }
}